
//饿汉模式
class Singleton {
    //static修饰,instance就变成了类成员,类成员的初始化发生在Singleton这个类被加载的时候
    private static  Singleton instance=new Singleton();
    public static Singleton getInstance() {
        return instance;
    }
    //单例模式最关键模式
    private Singleton() {
    }
}

class SingletonLazy{
    private static Object locker=new Object();

    //此处先把这个实例的引用设为null
    private static volatile SingletonLazy instance=null;
    public static SingletonLazy getInstance(){
        if(instance==null) {
            synchronized (locker) {
                if (instance == null) {
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }
    private SingletonLazy(){}
}

public class SingletonPattern {

    public static void main(String[] args) {
        SingletonLazy s1=SingletonLazy.getInstance();
        SingletonLazy s2=SingletonLazy.getInstance();
        System.out.println(s1==s2);
//        new SingletonLazy();
    }

    public static void main1(String[] args) {
        Singleton s1=Singleton.getInstance();
        Singleton s2=Singleton.getInstance();
        System.out.println(s1==s2);
//        new Singleton();
    }

}
